package org.eclipseuseradmin.internal.ui.security;

import java.io.IOException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.ConfirmationCallback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.TextOutputCallback;
import javax.security.auth.callback.UnsupportedCallbackException;

import org.eclipse.jface.wizard.IWizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipseuseradmin.internal.ui.wizards.LoginWizard;

public class OpenAutenticationWizardHandler implements CallbackHandler {

	public void handle(final Callback[] callbacks) throws IOException,
			UnsupportedCallbackException {

		final Display display = Display.getDefault();
		display.syncExec(new Runnable() {
			public void run() {

				WizardDialog dialog = new WizardDialog(
						display.getActiveShell(), getWizard(callbacks));
				dialog.create();
				dialog.open();

			}
		});
	}

	protected IWizard getWizard(Callback[] callbacks) {

		ConfirmationCallback confirmationCallback = null;
		TextOutputCallback messageCallback = null;
		NameCallback nameCallback = null;
		PasswordCallback passwordCallback = null;
		for (Callback callback : callbacks) {
			if (callback instanceof ConfirmationCallback) {
				confirmationCallback = (ConfirmationCallback) callback;
			} else if (callback instanceof TextOutputCallback) {
				messageCallback = (TextOutputCallback) callback;
			} else if (callback instanceof NameCallback) {
				nameCallback = (NameCallback) callback;
			} else if (callback instanceof PasswordCallback) {
				passwordCallback = (PasswordCallback) callback;
			}
		}

		LoginWizard wizard = new LoginWizard();
		wizard.init(confirmationCallback, messageCallback, nameCallback,
				passwordCallback);
		return wizard;
	}
}
